'use strict';

const { Service } = require('egg');

class WbUrlService extends Service {
  async list(options) {
    const { ctx: { model } } = this;
    const opt = {
      ...options,
      order: [[ 'created_at', 'desc' ], [ 'id', 'desc' ]],
    };
    if (opt.screen_name) {
      opt.where = {
        screen_name: opt.screen_name,
      };
    }
    return model.WbUrl.findAndCountAll(opt);
  }

  async find(id) {
    const { ctx: { model } } = this;
    const WbUrl = await model.WbUrl.findByPk(id, {});
    if (!WbUrl) {
      this.ctx.throw(404, 'WbUrl not found');
    }
    return WbUrl;
  }

  async create(WbUrl) {
    const { ctx: { model },app } = this;
    if (await app.redis.get('wbUrlData:读取列表')){
      await app.redis.del('wbUrlData:读取列表');
    }
    return model.WbUrl.bulkCreate(WbUrl);
  }

  async update({ id, updates }) {
    const { ctx: { model } } = this;
    const wbUrl = await model.WbUrl.findById(id);
    if (!wbUrl) this.ctx.throw(404, 'wbUrl not found');
    return wbUrl.update(updates);
  }

  // 删除
  async destroy(id) {
    const { ctx: { model },app } = this;
    const WbUrl = await model.WbUrl.findByPk(id); // 根据主键查
    await app.redis.del('wbUrlData:读取列表');
    if (!WbUrl) this.ctx.throw(404, 'WbUrl not found');
    return WbUrl.destroy();
  }
}

module.exports = WbUrlService;
